#include "pwm.h"
/**
 * @attention APB1总线的分频系数默认2,TIM2-TIM7的时钟频率2倍频
 * @brief 72000000/(arr+1)*(psc+1)
 * @brief 72000000/(59999+1)*(23+1)=50Hz(20ms) : [自动装栽值60000] [24分频]
 * @attention TIM_SetCompare3(TIM3, Compare3); //改变CCR从而改变占空比,Compare3(在自动装栽值arr范围内)
 */
void PWM_Init(uint16_t arr, uint16_t psc)
{
    TIM_OCInitTypeDef TIM_OCInitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    GPIO_InitTypeDef GPIO_InitStructure;
    // 总线时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);  // TIM3
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // PB
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);  //
    // GPIO
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;       // PB0  TIM3_CH3
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    // 定时器
    TIM_TimeBaseInitStructure.TIM_Period = arr;                     // 自动重装载
    TIM_TimeBaseInitStructure.TIM_Prescaler = psc;                  // 预分频系数
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
    // 输出比较单元与GPIO对应  TIM3_OC3
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;         // 计数值<CCR时输出有效电平
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; // 高电平有效
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = (arr + 1) / 2;    // 初始CCR,这里设置50%
    TIM_OC3Init(TIM3, &TIM_OCInitStructure);          // 输出比较单元有4个
    TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable); //
    TIM_Cmd(TIM3, ENABLE);
}
